package com.netsdk.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.netsdk.lht2.util.LogUtil;

public class SyncData implements Runnable{

	private Socket socket;
    private final LogUtil logUtil = new LogUtil("receive");;
    public SyncData(Socket socket) throws IOException {
		this.socket = socket;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		 try {
             while (testSocket()){
                 InputStream inputStream = socket.getInputStream();
                 BufferedReader reader =new BufferedReader( new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                 String body ;
                 while ((body = reader.readLine())!= null){
//                     JSONObject jsonObject = JSON.parseObject(body);
//                     System.out.println(body);
                     System.out.println("收到数据："+ LocalDateTime.now());
                     logUtil.log(LocalDateTime.now() +"收到："+body+"\n");
                     DataStore.set(body);
                 }
             }
         }catch (Exception e){
             e.printStackTrace();
         }
	}

    private boolean testSocket(){
        return socket.isConnected() && !socket.isClosed() && !socket.isInputShutdown() && !socket.isOutputShutdown();
    }
}
